package com.atguigu.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.properties.OrderProperties;
import com.atguigu.domain.Order;
import com.atguigu.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
//@RefreshScope
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;


    @Autowired
    private  OrderProperties orderProperties;

    @Value("${order.timeout}")
    public String timeout;

    @Value("${order.auto-confirm}")
    public String autoConfirm;

    /*
    @RefreshScope
    * 通过Value值获取配置文件中的数据
    * */
    @GetMapping("/getOrderProperties")
    public String getOrderProperties() {
        return timeout+","+autoConfirm;
    }



    /*
    * 使用 @ConfigurationProperties 自动绑定，动态刷新配置信息
    * */
    @GetMapping("/getOrderConfig")
    public String getOrderConfig() {
        return orderProperties.toString();
    }

    /*
    * 获取订单信息
    * */
    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable("id") int id) {
        Order order=orderService.getOrderById(id);
        return order;
    }

    /*
    * 秒杀订单信息---流控模式：测试--链路
    * */
    @GetMapping("/skillOrderById")
    @SentinelResource(value = "skillOrderById",fallback = "skillOrderByIdBlockHandler")
    public Order skillOrderById(@RequestParam("id") int id,@RequestParam("userId") String userId) {
        Order order=orderService.getOrderById(id);
        order.setId("skillOrderById222222");
        return order;
    }

    /*
    * 接口兜底回调
    * 测试：热点数据
    * 注意：默认的BlockExceptionHandler类是SentinelResourceAspect类，所以这个类不能被@Component注解，否则会报错
    *      使用 blockHandler 则使用 BlockException
    *      使用 fallback 则使用 Throwable
    * */
    public Order skillOrderByIdBlockHandler(int id, String userId, Throwable e) {
        Order order = new Order();
        order.setId(String.valueOf(id));
        order.setNickName("暂无数据，错误原因"+e.toString());
        return order;
    }

    @GetMapping("/writeDb")
    public String writeDb(){
        return "writeDb success";
    }

    @GetMapping("/readDb")
    public String readDb(){
        return "readDb success";
    }
}
